﻿
namespace LM.InterfacesFabricas.Fabricas
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    public class FabricaGenerica
    {
        private static List<Assembly> _assemblies;

        public static T Crie<T>(params object[] args)
        {
            var listaAssemblies = ObtenhaAssemblies();
            foreach (var assembly in listaAssemblies)
            {
                var tipoImplementacao = assembly.GetTypes().FirstOrDefault(t => t.GetInterfaces().Contains(typeof(T)));

                if (tipoImplementacao != null)
                {
                    return (T)Activator.CreateInstance(tipoImplementacao, args);
                }
            }

            return default(T);
        }

        private static List<Assembly> ObtenhaAssemblies()
        {
            if (_assemblies == null)
            {
                var caminhoCorrente = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var arquivos = Directory.GetFiles(caminhoCorrente, "LM*.dll");

                _assemblies = arquivos.Select(arquivo => Assembly.LoadFile(arquivo)).ToList();
            }

            return _assemblies;
        }
    }
}
